using System.Reflection;
using CMS.EFCore;
using CMS.Web.Attributes;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;

namespace CMS.Web.Filters;

public class UnitOfWorkFilter(MyDbContext myDbContext) : IAsyncActionFilter {
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) {
        var result = await next.Invoke();
        //有错误就不用保存了
        if (result.Exception != null) return;
        var controllerActionDesc = context.ActionDescriptor as ControllerActionDescriptor;
        if(controllerActionDesc == null) return;
        var unitAttribute = controllerActionDesc.MethodInfo.GetCustomAttribute(typeof(UnitOfWorkAttribute));
        if(unitAttribute == null) return;
        await myDbContext.SaveChangesAsync();
    }
}